// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// d [author] rhyme_lph
// g [email]  rhymelph@gmail.com
// e [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/views/employee_provider.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/form/down_button_form.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/employee_item.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class EmployeeView extends StatefulWidget {
  final String employeeStatus;

  const EmployeeView({Key key, this.employeeStatus}) : super(key: key);

  @override
  _EmployeeViewState createState() => _EmployeeViewState();
}

class _EmployeeViewState extends State<EmployeeView>
    with
        StatefulPresenter<EmployeeView, HrAndPayrollProvider, EmployeeProvider>,
        KeepAliveMixin {
  @override
  void initState() {
    if (widget.employeeStatus != null) {
      provider.employmentStatus = widget.employeeStatus;
    }
    super.initState();
  }

  @override
  Widget buildEmptyWidget(BaseProvider _, BuildContext context) {
    return ColoredBox(
      color: Colors.white,
      child: Column(
        children: [
          buildTopWidget,
          Expanded(
            child: super.buildEmptyWidget(provider, context),
          ),
        ],
      ),
    );
  }

  Widget get buildTopWidget => !Config.hasPermission(PermissionUtils.hrPayroll)
      ? Container(
          height: getDp(20),
        )
      : Column(
          children: [
            AppSpaces.h25,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            AppSpaces.h20,
            listBuilder<String>(
              selector: (_, __) => __.employmentStatus,
              builder: (BuildContext context, String value, Widget child) =>
                  DownButtonForm(
                title: LanguageUtils.translateStatus(value),
                onTap: provider.onChangeType,
              ),
            ),
            AppSpaces.h20,
          ],
        );

  @override
  Widget buildWidget(BuildContext context) => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            buildTopWidget,
            Expanded(
              child: listBuilder<Map<String, List<EmployeeContactEntity>>>(
                selector: (_, __) =>
                    Map<String, List<EmployeeContactEntity>>.from(__.groupMap),
                builder: (BuildContext context,
                        Map<String, List<EmployeeContactEntity>> value,
                        Widget child) =>
                    SmartRefresher(
                  controller: provider.refreshController,
                  onRefresh: provider.onRefresh,
                  onLoading: provider.onLoadMore,
                  enablePullUp: false,
                  child: CustomScrollView(
                    controller: provider.controller,
                    slivers: buildSearchWidget(),
                  ),
                ),
              ),
            ),
          ],
        ),
      );

  List<Widget> buildSearchWidget() {
    return provider.groupMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<EmployeeContactEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<EmployeeContactEntity> data, int i) {
    return PressedOpacityButton(
      onPressed: () => provider.onNavDetail(data[i]),
      child: EmployeeItem(
        title: data[i].name,
        content: data[i].title ?? '',
        badge: data[i].actionCount,
        status: data[i].resignedAt != null
            ? 'resigned'
            : (data[i].isCompleted != 1 ? S.current.incomplete : null),
        isLastItem: data.length == i + 1,
      ),
    );
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
